package com.jg.blog.manager;

import com.jg.blog.constant.RedisKeyConstant;
import com.jg.blog.utils.StringUtils;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

/**
 * @Description 解决登录验证问题
 * @Date: 2020/6/3 10:20
 * @Author: Dream
 * @version: 1.0
 */
@Configuration
@SuppressWarnings("all")
public class ShiroTokenManager extends DefaultWebSessionManager {
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        HttpServletRequest http = WebUtils.toHttp(request);
        // 取出token
        String token = http.getHeader(RedisKeyConstant.TOKEN_KEY);
        // 使用token获取登录用户信息
        Object user = redisTemplate.opsForValue().get(RedisKeyConstant.TOKEN_KEY + ":" + token);
        // 如果user为空说明这个token不合法
        if (user == null) {
            return null;
        }
        if (StringUtils.isNotBlank(token)) {
            // 不为空，直接返回
            return token;
        }
        return super.getSessionId(request, response);
    }
}
